package org.ykhl.mq.commons;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by zkf on 2015/11/25.
 */
public abstract class StoppableInfiniteRunnable implements Runnable{
    private static final Logger LOG = LoggerFactory.getLogger(StoppableInfiniteRunnable.class);

    private volatile boolean isRunning = false;

    public abstract void beforeRun();
    public abstract void doRun();
    public abstract void afterRun();

    public void stop(){
        if(! isRunning)
            return;

        isRunning = false;
    }

    @Override
    public void run(){
        isRunning = true;
        beforeRun();
        try {
            while (isRunning)
                doRun();
        } catch (Exception e) {
            isRunning = false;
            LOG.error("uncaught exception from subclass, thread will stop", e);
        } finally {
            afterRun();
        }
    }

}
